<?php
/**
 * Mobile Area Db.
 */
class MobileAreaDb
{

    /**
     * DB dir path.
     */
    private $db_path = './data/';

    /**
     * DB file path.
     */
    private $file_path = '';

    /**
     * Init file path.
     *
     * @param string $db_name
     *   The db name.
     */
    public function __construct(string $db_name = '') {
        if ($db_name === '') {
            die("db_name can't be empty");
        }
        $this->file_path = $this->db_path . $db_name . '.json';
    }

    /**
     * Check file exists.
     */
    public function has_file() {
        return is_file($this->file_path);
    }

    /**
     * Add data
     *
     * @param array $data
     *   The data need add.
     */
    public function add(array $data = []) {
        return $this->writeContent($data);
    }

    /**
     * Find data by id.
     *
     * @param string $id
     *   The area id.
     */
    public function findByPk(string $id = '') {
        $data = $this->readContent();
        return $data[$id] ?? [];
    }

    /**
     * Encode data.
     *
     * @param array $data
     *   The data need encode.
     */
    private function encodeData(array $data = []) {
        return igbinary_serialize($data);
    }

    /**
     * Decode data.
     *
     * @param string $string
     *   The data need decode.
     */
    private function decodeData(string $string = '') {
        if (empty($string)) {
            return false;
        }
        return igbinary_unserialize($string);
    }

    /**
     * Read data.
     */
    private function readContent() {
        static $content_data = [];
        if (!isset($content_data[$this->file_path])) {
            $content_data[$this->file_path] = file_get_contents($this->file_path);
            $content_data[$this->file_path] = $this->decodeData($content_data[$this->file_path]);
        }
        return $content_data[$this->file_path];
    }

    /**
     * Write data.
     *
     * @param array $data
     *   The data need write.
     */
    private function writeContent(array $data = []) {
        if (empty($data)) {
            return false;
        }
        return file_put_contents($this->file_path, $this->encodeData($data), LOCK_EX);
    }
}
